package csc.fresher.finalgroupfour.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.fresher.finalgroupfour.domain.Transaction;

@Repository("transactionDAO")
public class TransactionDAO {
	@PersistenceContext
	private EntityManager em; // Entity Manager is acquired by container.
	
	/**
	 * Add a new transaction.
	 * @param transaction
	 */
	@Transactional
	public void addTransaction(Transaction transaction) {
		em.persist(transaction);
	}
	
	/**
	 * List all transactions in DB.
	 * @return
	 */
	@Transactional
	public List<Transaction> listTransactions() {
		List<Transaction> transactions = new ArrayList<Transaction>();
		TypedQuery<Transaction> query = em.createQuery("SELECT a FROM Transaction a", Transaction.class);
		
		transactions = query.getResultList();
		if (transactions.size() > 0) {
			return transactions;
		}
		return null;
	}
	
	/**
	 * Update a transaction's information
	 * @param transaction
	 */
	@Transactional
	public void updateTransaction(Transaction transaction) {
		em.merge(transaction);
	}
	
	/**
	 * Remove a transaction from database.
	 * @param transaction
	 */
	@Transactional
	public void deleteTransaction(Transaction transaction) {
		em.remove(transaction);
	}
	
	/**
	 * Find weather a transaction existed or not.
	 * @param transaction
	 * @return
	 */
	@Transactional
	public boolean findTransaction(Transaction transaction) {
		return em.contains(transaction);
	}
}
